package com.jasmine.bjstkserver.server.param;

import com.jasmine.bjstkserver.mapper.ParamMapper;
import com.jasmine.core.constants.BjsConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 系统参数
 * @author jasmineXz
 */
@Service
public class ParamServiceImpl implements ParamService {

    @Autowired
    private ParamMapper paramMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<ParamEntity> findAll() {
        return paramMapper.findAll();
    }


    @Override
    public ParamEntity findOne(Integer paramId) {
        ParamEntity paramEntity = (ParamEntity) redisTemplate.opsForValue().get(BjsConstants.Redis.PARAM_ID + paramId);
        if(paramEntity == null) {
            paramEntity = paramMapper.selectByPrimaryKey(paramId);
            Optional.ofNullable(paramEntity).orElseThrow(() -> new IllegalArgumentException("参数不存在:" + paramId));
            redisTemplate.opsForValue().set(
                    BjsConstants.Redis.PARAM_ID + paramId,
                    paramEntity,
                    BjsConstants.Redis.TIME_7_DAY,
                    BjsConstants.Redis.REDIS_SECONDS
            );
        }
        return paramEntity;
    }


    @Override
    public void clearAll() {
        List<ParamEntity> params = paramMapper.findAll();
        List<String> paramIds = new ArrayList<>();
        for (ParamEntity param : params) {
            paramIds.add(BjsConstants.Redis.PARAM_ID + param.getParamId());
        }
        redisTemplate.delete(paramIds);
    }
}
